package demo1;

import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:顺序栈
 * User: LianBao
 * Date: 2024-04-01
 * Time: 14:02
 */
public class myStack<E> {
    public Object[] arr;
    public int curSize;

    public myStack() {
        this.arr = new Object[10];
    }

    //入栈
    public E push(E val) {
        //满了,扩容
        if (curSize == arr.length) {
            this.arr = Arrays.copyOf(this.arr, 2 * this.arr.length);
        }
        arr[curSize] = val;
        curSize++;

        return val;
    }

    //出栈
    public E pop() {
        if (curSize == 0) {
            return null;
        }
        Object ret = this.arr[curSize - 1];
        curSize--;
        return (E) ret;
    }

    //获取栈顶元素,不删除
    public E peek() {
        if (curSize == 0) {
            return null;
        }
        Object ret = this.arr[curSize - 1];
        return (E) ret;
    }

    //判断是否为空
    public boolean empty() {
        return curSize == 0;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (int i = 0; i < curSize; i++) {
            str.append(arr[i]);
            if (i < curSize - 1) {
                str.append(",");
            }
        }
        str.append("]");
        return str.toString();
    }
}
